// @import
import HeroCtrl from "./HeroCtrl";

// @const
const RED_BLINK: cc.Color = cc.color(255, 100, 100);
const HP_IMG_MAX_WIDTH: number = 35;

/**
 * 执行减血
 * 
 * @param SELF this 指针
 * @param nSubtractHP 减血量
 */
export function __doDamage(SELF: HeroCtrl, nSubtractHP: number): void {
    if (null == SELF ||
        0 == Math.abs(nSubtractHP)) {
        return;
    }

    nSubtractHP = Math.abs(nSubtractHP);
    SELF._nCurrHP = Math.max(0, SELF._nCurrHP - nSubtractHP);

    // 缩短血条
    let nHPPercentage: number = (SELF._nCurrHP / SELF._nMaxHP) * HP_IMG_MAX_WIDTH;
    cc.find("Holder_NameAndHP/Sprite_HP_1", SELF.node).width = nHPPercentage;
    
    let oHeroNode: cc.Node = cc.find("Spine_Hero", SELF.node);

    let funTw = cc.tween;

    funTw(oHeroNode)
        .delay(0.2)
        .sequence(
            funTw().to(0.1, { color: RED_BLINK, })
                .call(() => { 
                    __showSubtractHP(SELF, nSubtractHP); 
                }),

            funTw().to(0.1, { color: cc.Color.WHITE, }),
        )
        .start();

    if (SELF._nCurrHP <= 0) {
        SELF.doDie();
    }
}

/**
 * 显示减血
 * 
 * @param SELF this 指针
 * @param nSubtractHP 减血量
 */
function __showSubtractHP(SELF: HeroCtrl, nSubtractHP: number): void {
    if (null == SELF || 
        nSubtractHP <= 0) {
        return;
    }

    nSubtractHP = Math.abs(nSubtractHP);

    // 显示在世界位置
    let oShowAtWorldPos: cc.Vec2 = SELF.node.convertToWorldSpaceAR(cc.Vec2.ZERO);
    oShowAtWorldPos.x += Math.random() * 99 - 50;
    oShowAtWorldPos.y += Math.random() * 32 - 16 + 144;
    oShowAtWorldPos = cc.Canvas.instance.node.convertToNodeSpaceAR(oShowAtWorldPos);

    // 创建减血节点
    let oSubtractHPNode: cc.Node = cc.find("/Canvas/_Prefab/Label_SubtractHP");
    oSubtractHPNode = cc.instantiate(oSubtractHPNode);

    oSubtractHPNode.getComponent(cc.Label).string = nSubtractHP.toString();
    oSubtractHPNode.x = oShowAtWorldPos.x;
    oSubtractHPNode.y = oShowAtWorldPos.y;
    oSubtractHPNode.scale = 2.4;
    oSubtractHPNode.opacity = 0;
    cc.Canvas.instance.node.addChild(oSubtractHPNode);

    let funTw = cc.tween;

    funTw(oSubtractHPNode)
        .sequence(
            funTw().to(0.15, { scale: 1.0, opacity: 255, }),
            funTw().by(0.10, { y: 50, }),
            funTw().by(0.90, { y: 10, }),
        )
        .call(() => { oSubtractHPNode.destroy(); })
        .start();
}
